package com.cdu.ai_intelligent_teaching_and_training_system.controller;

import com.cdu.ai_intelligent_teaching_and_training_system.dto.ApiResponse;
import com.cdu.ai_intelligent_teaching_and_training_system.entity.Exam;
import com.cdu.ai_intelligent_teaching_and_training_system.entity.UserAnsweredQuestion;
import com.cdu.ai_intelligent_teaching_and_training_system.service.ExamService;
import com.cdu.ai_intelligent_teaching_and_training_system.service.UserAnsweredQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/exams")
@CrossOrigin(origins = "*")
public class ExamController {
    
    @Autowired
    private ExamService examService;
    
    @Autowired
    private UserAnsweredQuestionService userAnsweredQuestionService;
    
    @GetMapping
    public ResponseEntity<ApiResponse<List<Exam>>> getAllExams() {
        try {
            List<Exam> exams = examService.findAll();
            return ResponseEntity.ok(ApiResponse.success(exams));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取考试列表失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Exam>> getExamById(@PathVariable Long id) {
        try {
            Exam exam = examService.findById(id).orElse(null);
            if (exam == null) {
                return ResponseEntity.ok(ApiResponse.error("考试不存在"));
            }
            return ResponseEntity.ok(ApiResponse.success(exam));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取考试详情失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/course/{courseId}")
    public ResponseEntity<ApiResponse<List<Exam>>> getExamsByCourse(@PathVariable Long courseId) {
        try {
            List<Exam> exams = examService.findByCourseId(courseId);
            return ResponseEntity.ok(ApiResponse.success(exams));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取课程考试失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/upcoming")
    public ResponseEntity<ApiResponse<List<Exam>>> getUpcomingExams() {
        try {
            List<Exam> exams = examService.findUpcomingExams();
            return ResponseEntity.ok(ApiResponse.success(exams));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取即将到来的考试失败：" + e.getMessage()));
        }
    }
    
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<List<Exam>>> searchExams(@RequestParam String title) {
        try {
            List<Exam> exams = examService.findByTitleContaining(title);
            return ResponseEntity.ok(ApiResponse.success(exams));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("搜索考试失败：" + e.getMessage()));
        }
    }
    
    @PostMapping
    public ResponseEntity<ApiResponse<Exam>> createExam(@Valid @RequestBody Exam exam) {
        try {
            Exam savedExam = examService.save(exam);
            return ResponseEntity.ok(ApiResponse.success("考试创建成功", savedExam));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("创建考试失败：" + e.getMessage()));
        }
    }
    
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Exam>> updateExam(@PathVariable Long id, @Valid @RequestBody Exam exam) {
        try {
            Exam existingExam = examService.findById(id).orElse(null);
            if (existingExam == null) {
                return ResponseEntity.ok(ApiResponse.error("考试不存在"));
            }
            
            exam.setExamId(id);
            Exam updatedExam = examService.save(exam);
            return ResponseEntity.ok(ApiResponse.success("考试更新成功", updatedExam));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("更新考试失败：" + e.getMessage()));
        }
    }
    
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<String>> deleteExam(@PathVariable Long id) {
        try {
            Exam existingExam = examService.findById(id).orElse(null);
            if (existingExam == null) {
                return ResponseEntity.ok(ApiResponse.error("考试不存在"));
            }
            
            examService.deleteById(id);
            return ResponseEntity.ok(ApiResponse.success("考试删除成功", null));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("删除考试失败：" + e.getMessage()));
        }
    }

    // 新增：获取指定考试的前10条答题记录
    @GetMapping("/{id}/answered-questions")
    public ResponseEntity<ApiResponse<List<UserAnsweredQuestion>>> getTop10AnsweredQuestions(@PathVariable Integer id) {
        try {
            List<UserAnsweredQuestion> list = userAnsweredQuestionService.getTop10ByExamId(id);
            return ResponseEntity.ok(ApiResponse.success(list));
        } catch (Exception e) {
            return ResponseEntity.ok(ApiResponse.error("获取答题记录失败：" + e.getMessage()));
        }
    }
} 